package k8ssvc

import (
	"context"
	"deployment-service/domain"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	metrics "k8s.io/metrics/pkg/client/clientset/versioned"
	"k8s.io/metrics/pkg/client/clientset/versioned/typed/metrics/v1beta1"
)

type metricsAdapter struct {
	ctx       context.Context
	mc *metrics.Clientset
	nodeMc v1beta1.NodeMetricsInterface
}

func (m *metricsAdapter)getNodeMetricses(nodeName string)  {
	m.nodeMc.Get(m.ctx, nodeName, metav1.GetOptions{})
}

func (m *metricsAdapter) GetNodeData() v1beta1.NodeMetricsInterface {
	return m.nodeMc
}

func (m *metricsAdapter) GetPodData(namespace string) v1beta1.PodMetricsInterface {
	return m.mc.MetricsV1beta1().PodMetricses(namespace)
}

func (m *metricsAdapter) GetPodMetricsData(namespace string) ([]domain.K8sMetricsData, error) {
	podData := m.GetPodData(namespace)
	podMetrics, err := podData.List(m.ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err
	}

	var podResouces []domain.K8sMetricsData

	for _, podMetric := range podMetrics.Items {
		podContainers := podMetric.Containers
		podName := podMetric.ObjectMeta.Name
		for _, container := range podContainers {
			cpuQuantity := container.Usage.Cpu().AsApproximateFloat64()
			memQuantity, ok := container.Usage.Memory().AsInt64()

			if !ok {
				continue
			}
			containerName := container.Name
			if containerName == "POD" {
				continue
			}
			podResouces = append(podResouces, domain.K8sMetricsData {
				Cpu: cpuQuantity,
				Mem: memQuantity,
				PodName: podName,
			})
		}
	}

	return podResouces, nil
}